// pages/write-off/detail.js
const wxParse = require('../../vendor/wxParse/wxParse')
const numeral = require("../../vendor/numeral/numeral.min")
const format = require('../../utils/format.js')
const app = getApp()
Page({

    data: {
        isSpec: false,
        num: 1,
        isStart: true,
        isEnd: false
    },

    onLoad: function(options) {
        this.setData(options)
        app.share(options.pmid)
        this.loadData()
        this.loadGoodsSku()
    },
    loadData() {
        wx.showLoading({
            title: '加载中...',
        })
        app.http.get('hx-goods/info?id=' + this.data.id).then(res => {
            let now_time = new Date().getTime()
            let start = res.data.extend.rush_start_at
            let end = res.data.extend.rush_end_at
            res.data.isStart = start <= 0 || (start * 1000) <= now_time
            res.data.isEnd = end > 0 && (end * 1000) <= now_time
            res.data.activity_start = format.dateformat.format(new Date((start * 1000)))
            res.data.activity_end = format.dateformat.format(new Date((end * 1000)))
            this.setData(res.data)
            wx.setNavigationBarTitle({
                title: this.data.title
            })
            wxParse.wxParse("content", "html", this.data.extend.content, this, 15)
            wx.hideLoading()
            wx.stopPullDownRefresh()
        })
    },
    loadGoodsSku() {
        app.http.get('hx-goods/sku?goods_id=' + this.data.id).then(res => {
            res.data.spec_list.map(o => {
                    o.selected = -1
                    return o
                }),
                res.data.selectedSku = false
            this.setData(res.data)
            wx.hideLoading()
        })
    },
    callSellerPhone() {
        wx.makePhoneCall({
            phoneNumber: this.data.seller_info.phone
        })
    },
    openLocation() {
        let longitude = parseFloat(this.data.seller_info.lng)
        let latitude = parseFloat(this.data.seller_info.lat)
        wx.openLocation({
            name: this.data.seller_info.name,
            address: this.data.seller_info.address,
            longitude,
            latitude,
            scale: 18,
        })
    },
    isShare() {
        this.setData({
            sharePop: !this.data.sharePop
        })
    },
    isPoster() {
        this.setData({
            poster: !this.data.poster
        })
    },
    selectSpec() {
        this.setData({
            isSpec: !this.data.isSpec
        })
    },
    /**
     * 选择商品规格
     */
    clickSpec(evt) {
        const {
            row,
            col
        } = evt.currentTarget.dataset
        this.setData({
            [`spec_list[${row}].selected`]: col
        })
        let skuName = this.data.spec_list.map(o => {
            return o.sku_items[o.selected] ? o.sku_items[o.selected] : "--"
        }).join("#")
        this.setData({
            selectedSku: this.data.sku_list.find(o => o.name == skuName),
        })
        this.computePrice()
    },
    /**
     * 数量加减
     */
    num_plus: function() {
        let num = this.data.num + 1
        this.updateNum(num)
    },

    num_minus: function() {
        let num = this.data.num - 1
        this.updateNum(num)
    },
    updateNum: function(num) {
        if (num < 1) num = 1
        if (num > this.data.max_amount) {
            num = this.data.max_amount
        }
        this.setData({
            num,
        })
        this.computePrice()
    },
    /**
     * 计算总价
     */
    computePrice() {
        let sku = this.data.selectedSku
        let p = sku ? sku.mall_price : this.data.mall_price
        console.log(p, 'p')
        p = Math.max(0.01, p)
        this.setData({
            totalPrice: numeral(p * this.data.num).format('0,0.00')
        })
    },
    toPay() {
        let data = this.data
        const ps = ["id=" + this.data.id, "num=" + this.data.num]
        var sel = this.data.spec_list.filter(function(o) {
            return !o.sku_items[o.selected]
        })
        if (sel.length) {
            app.wxToast.warn('请选择' + sel[0].name)
            return
        }
        if (this.data.selectedSku && this.data.selectedSku.stock <= 0) {
            return
        }
        this.data.selectedSku && ps.push("sku_id=" + this.data.selectedSku.sku_id)
        wx.navigateTo({
            url: '/pages/write-off/order-ok?' + ps.join("&"),
        })
    },
    saveImageToPhotosAlbum() {
        wx.showLoading({
            title: '生成海报中...'
        })
        var that = this;
        //设置画板显示，才能开始绘图
        that.setData({
            canvasHidden: false,
            sharePop: false
        })

        function download(url) {
            return new Promise(resolve => {
                wx.downloadFile({
                    url: url,
                    success: res => {
                        resolve(res.tempFilePath);
                    }
                })
            })
        }
        var unit = app.scrollWidth / 375
        var ctx = wx.createCanvasContext('poster')
        ctx.setFillStyle('#fff')
        ctx.font = "10px PingFang SC"
        ctx.fillRect(0, 0, unit * 280, unit * 420)

        download(that.data.extend.background_image).then(r => {
            ctx.drawImage(r, 0, 0, unit * 280, unit * 420);
            return download(that.data.extend.qr_code)
        }).then(r => {
            ctx.drawImage(r, unit * 17, unit * 377, unit * 37, unit * 37);
        }).then(r => {
            ctx.draw(false, function() {
                that.setData({
                    poster: true,
                })
                wx.hideLoading()
            })

        })
    },
    savePoster() {
        var that = this
        var unit = app.scrollWidth / 375
        wx.showLoading({
            title: '保存中',
        })
        wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            width: unit * 280,
            height: unit * 430,
            destWidth: unit * 1680,
            destHeight: unit * 2580,
            quality: 1,
            canvasId: 'poster',
            success: res => {
                that.setData({
                    scope: false
                })
                wx.saveImageToPhotosAlbum({
                    filePath: res.tempFilePath,
                    success: (res) => {
                        wx.showModal({
                            title: '温馨提示',
                            content: '核销商品海报已保存到手机相册',
                            showCancel: false,
                            confirmColor: '#ff5400'
                        })
                        wx.hideLoading()
                        that.setData({
                            canvasHidden: true,
                            poster: false,
                        })
                    },
                    fail: (err) => {
                        wx.hideLoading()
                        wx.showToast({
                            title: '保存失败，请稍后再试',
                            icon: 'none'
                        })
                        if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                            that.setData({
                                scope: true
                            })
                        }
                    }
                })
            }
        })
    },
    onPullDownRefresh() {
        this.loadData()
        this.loadGoodsSku()
    },
    onShareAppMessage: function(e) {
        if (e.form = "button") {
            this.isShare()
        }
        let imageUrl = this.data.forward_image
        return app.getShareObj(this.data.title, {
            id: this.data.id
        }, imageUrl)
    }
})